package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    //对表关联对象进行注入
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;


    @Override
    public void remove(Long id) {
        //3.在categoryServiceImpl中调用另外两个表根据category_id查询条目数的方法
        //3.1如果查到的setmeal数据数>0,直接抛出异常,让全局异常处理器处理,不进行删除操作
        LambdaQueryWrapper<Dish> dishqueryWrapper = new LambdaQueryWrapper<>();
        dishqueryWrapper.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishqueryWrapper);
        if (dishCount > 0) {
            //这里需要自定义异常类,将异常设置为运行时异常,并将异常信息抛给父类
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        //3.2如果查到的dish数据数>0,直接抛出异常,让全局异常处理器处理,不进行删除操作
        LambdaQueryWrapper<Setmeal> setmealqueryWrapper = new LambdaQueryWrapper<>();
        setmealqueryWrapper.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealqueryWrapper);
        if (setmealCount > 0) {
            //这里需要自定义异常类,将异常设置为运行时异常,并将异常信息抛给父类
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        //3.3上述代码全部通过后,执行删除操作
        super.removeById(id);
    }
}
